package com.ydj.framework.config;

import com.ydj.BaseConst;
import com.ydj.framework.interceptor.AuthBaseInterceptor;
import com.ydj.framework.interceptor.IdempotenceInterceptor;
import com.ydj.framework.interceptor.LogInterceptor;
import com.ydj.framework.interceptor.RateLimitInterceptor;
import com.ydj.framework.resolver.ExtArgumentResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;
import java.util.stream.Collectors;

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
	@Autowired
	private LogInterceptor logInterceptor;

	@Autowired
    private IdempotenceInterceptor idempotenceInterceptor;

    @Autowired
    private List<AuthBaseInterceptor> authInterceptorList;

    @Autowired
    private List<BaseConst> constList;

    @Autowired
    private ExtArgumentResolver extArgumentResolver;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        List<String> pathPatterns = constList.stream()
                .map(item-> item.getBaseUrl() + "/**")
                .collect(Collectors.toList());

        // 多个拦截器组成一个拦截器链
        // addPathPatterns 用于添加拦截规则，/**表示拦截所有请求
        // excludePathPatterns 用户排除拦截

        // 全局限流
        registry.addInterceptor(new RateLimitInterceptor())
                .addPathPatterns(pathPatterns);

        //幂等性
        registry.addInterceptor(idempotenceInterceptor)
                .addPathPatterns(pathPatterns);

        // 全局打LOG
        registry.addInterceptor(logInterceptor)
                .addPathPatterns("/common/**")
                .addPathPatterns(pathPatterns)
                .order(Ordered.HIGHEST_PRECEDENCE);

        // 验权的拦截器
        for (AuthBaseInterceptor authInterceptor : authInterceptorList) {
            registry.addInterceptor(authInterceptor)
                    .addPathPatterns(authInterceptor.getPathPatterns());
        }
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(extArgumentResolver);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/robots.txt").addResourceLocations("classpath:/robots/robots.txt");
        registry.addResourceHandler("/WW_verify_**.txt").addResourceLocations("classpath:/wc-cert/");
    }
}